package com.xuzimian.globaldemo.rpc.rmi;

import com.xuzimian.globaldemo.rpc.rmi.remote.Student;
import com.xuzimian.globaldemo.rpc.rmi.remote.StudentService;
import com.xuzimian.globaldemo.rpc.rmi.remote.StudentServiceImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
import java.util.List;




/**
 * @program: global-demo
 * @description: 发布rmi服务和调用rmi服务
 * @author: xzm
 * @create: 2019-01-10 10:24
 **/
public class RMIDemo {

    @BeforeEach
    public void piublisRMI(){
        try {
            StudentService studentService=new StudentServiceImpl();
            LocateRegistry.createRegistry(5008);//定义端口号
            Naming.rebind("rmi://127.0.0.1:5008/StudentService", studentService);
            System.out.println("服务已启动");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public  void  callRmiServiceSucess(){
        try {
            StudentService studentService=(StudentService) Naming.lookup("rmi://127.0.0.1:5008/StudentService");
            List<Student> list = studentService.getList();
            for (Student s : list) {
                System.out.println("姓名："+s.getName()+",年龄："+s.getAge());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 调用远程rmi接口必须获得远程rmi服务提供的类，否则类型转换异常
     */
    @Test
    public  void  callRmiServiceFail(){
        try {
            com.xuzimian.globaldemo.rpc.rmi.local.StudentService studentService=(com.xuzimian.globaldemo.rpc.rmi.local.StudentService) Naming.lookup("rmi://127.0.0.1:5008/StudentService");
            List<com.xuzimian.globaldemo.rpc.rmi.local.Student> list = studentService.getList();
            for (com.xuzimian.globaldemo.rpc.rmi.local.Student s : list) {
                System.out.println("姓名："+s.getName()+",年龄："+s.getAge());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
